#ifndef __TTHREAD_H__
#define __TTHREAD_H__

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <process.h>

#pragma once

class IThreadContext
{
public:
	virtual void TaskMaintainance() = 0;
};

class TThread
{
public:
	virtual ~TThread()
	{
		Destroy();
	}
	BOOL Create( IThreadContext* pThread )
	{
		m_hExitEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
		if( m_hExitEvent == NULL )
			return FALSE;

		m_hThread = (HANDLE)_beginthreadex(NULL, 0, &TThread::ThreadEntry, this, CREATE_SUSPENDED, &m_nThreadID);
		m_pThread = pThread;
		m_bRunning = FALSE;
		return ( m_hThread != NULL );
	}

	DWORD Suspend()
	{
		return SuspendThread( m_hThread );
	}

	DWORD Resume()
	{
		return ResumeThread( m_hThread );
	}

	VOID Destroy()
	{
		SetEvent(m_hExitEvent);
		WaitForSingleObject( m_hThread, INFINITE );
		CloseHandle(m_hThread);
		CloseHandle(m_hExitEvent);
	}

	static TThread* NewThread( IThreadContext* pThread )
	{
		TThread* pNewThread = new TThread();
		pNewThread->Create( pThread );
		return pNewThread;
	}

private:
	static UINT WINAPI ThreadEntry(LPVOID lParam)
	{
		TThread* pThis = (TThread*)lParam;
		while( TRUE )
		{
			DWORD dwObject = WaitForSingleObject( pThis->m_hExitEvent, 5 );

			if( dwObject == WAIT_OBJECT_0 )
			{
				break;
			}
			else
			{
				pThis->m_pThread->TaskMaintainance();
			}
		}

		_endthreadex(0);
		return 0;
	}

private:
	HANDLE	m_hExitEvent;
	HANDLE	m_hThread;
	UINT		m_nThreadID;
	IThreadContext*	m_pThread;
	BOOL		m_bRunning;
};


#endif //
